//
//  ComposeViewController.m
//  SinaWeibo
//
//  Created by Apple on 16/8/16.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "ComposeViewController.h"
#import "InputTextView.h"
#import "InputToolBar.h"
#import "PhotoSelectViewController.h"

@interface ComposeViewController ()<UITextViewDelegate>

@property (weak,nonatomic) InputTextView *inputTextView;

@property (nonatomic,weak) InputToolBar *toolBar;

@property (weak, nonatomic) IBOutlet UIView *inputContainer;

@property (strong, nonatomic) PhotoSelectViewController *photoSelectViewController;

@end


@implementation ComposeViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.布置发送界面并且监听文本输入框
    [self setComposeView];
    
    //2.添加inputToolBar
    [self setInputToolBar];

    
}

//添加inputToolBar
-(void)setInputToolBar{
    
    CGRect toolBarFrame = CGRectMake(0, 667, self.view.frame.size.width, 38);
    
    
    InputToolBar *toolBar = [[InputToolBar alloc]initWithFrame:toolBarFrame];
    
    self.toolBar = toolBar;
    
    [self.view addSubview:toolBar];
    
    //监听键盘show 和 hide方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

-(void)keyboardWillShow:(NSNotification *)notification{
    
//    UIKeyboardAnimationCurveUserInfoKey = 7;
//    UIKeyboardAnimationDurationUserInfoKey = "0.25";
//    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
//    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
//    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
//    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
//    UIKeyboardIsLocalUserInfoKey = 1;
    
    NSLog(@"show%@",notification.userInfo);
    
    NSTimeInterval timeInterval = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    UIViewAnimationOptions animationCurve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    CGRect keyBoardRect = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    
    //toolBar跟着键盘动画弹出
    [UIView animateWithDuration:timeInterval delay:0 options:animationCurve animations:^{
        
        NSLog(@"弹出前%@",NSStringFromCGRect(self.toolBar.frame));
        
        //设置到输入框下面
//        self.toolBar.transform = CGAffineTransformMakeTranslation(0,-self.view.frame.size.height + CGRectGetMaxY(self.inputTextView.frame));
        
        //设置到键盘上面
        self.toolBar.transform = CGAffineTransformMakeTranslation(0,-(self.toolBar.frame.size.height + keyBoardRect.size.height));
        
        NSLog(@"弹出后%@",NSStringFromCGRect(self.toolBar.frame));
        
    } completion:nil];
    
}

-(void)keyboardWillHide:(NSNotification *)notification{
    NSLog(@"hide");
    NSTimeInterval timeInterval = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    UIViewAnimationOptions animationCurve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    //toolBar跟着键盘动画弹出
    [UIView animateWithDuration:timeInterval delay:0 options:animationCurve animations:^{
        
        self.toolBar.transform = CGAffineTransformIdentity;
        
        
    } completion:nil];

}

//设置发送微博界面
-(void)setComposeView{
    
    self.view.backgroundColor = [UIColor redColor];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem setNavItemWithTitle:@"取消" target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem setNavItemWithTitle:@"发送" normalColor:[UIColor orangeColor] highlightedColor:[UIColor grayColor] target:self action:@selector(compose)];
    
    CGRect labelFrame = CGRectMake(0, 0, self.view.frame.size.width, 200);
//    CGRect frame = self.inputContainer.frame;
    
    InputTextView *inputTextView = [[InputTextView alloc]initWithFrame:labelFrame];
    
    self.inputTextView = inputTextView;
    
    inputTextView.alwaysBounceVertical = YES;
    
    inputTextView.delegate = self;
    
    inputTextView.placeholderText = @"input What u want to share!";
    
    [self.inputContainer addSubview:inputTextView];
    
    NSLog(@"inputcontain%@",NSStringFromCGRect(self.inputContainer.frame));
    
    
    NSLog(@"inpuview%@",NSStringFromCGRect(self.inputTextView.frame));
    
    
    //用通知或者代理实现输入框变化的监听。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(whileTextViewChange) name:UITextViewTextDidChangeNotification object:nil];
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    
}

//实现监听通知方法
-(void)whileTextViewChange{
    self.inputTextView.placehoderLabel.hidden = (self.inputTextView.text.length > 0);
    self.navigationItem.rightBarButtonItem.enabled = (self.inputTextView.text.length > 0);
    
}

//移除通知
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

#pragma mark - 微博取消发送。
-(void)cancel{
    //先收回键盘
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    //在收回界面
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 发送微博
-(void)compose{
    
    
    
    if (self.photoSelectViewController.images.count > 0) {
        [self composeStatusWithImage];
    }else{
        [self composeStatusWithoutImage];
    }
    
    
}

-(void)composeStatusWithImage{
    
    //创建管理者
    AFHTTPSessionManager *sessionManger = [AFHTTPSessionManager manager];
    
    //发送请求
    
    AcountModel *acount = [AcountModel acountModelFromSandbox];
    
    //设置参数
    NSDictionary *parameters = @{
                                 @"access_token":acount.access_token,
                                 @"status":self.inputTextView.text
                                 };
    
    NSString *stringURL = @"https://api.weibo.com/2/statuses/update.json";
    
    [sessionManger POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
//        取出要转换成二进制数据的图片
        UIImage *image = [self.photoSelectViewController.images firstObject];
        
//        转化
        NSData *imageData = UIImagePNGRepresentation(image);
        
        NSString *fileName = [NSString stringWithFormat:@"%@",image];
        
        
        [formData appendPartWithFileData:imageData name:@"pic" fileName:fileName mimeType:@"image/png"];
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"发送成功");
        
        //1.发送界面收回
        //1.1先收回键盘
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        //2.显示发送成功界面
        [SVProgressHUD setStatus:@"发送成功"];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@－－发送失败",error);
        [SVProgressHUD setStatus:@"发送失败"];
    }];
    
    
}

-(void)composeStatusWithoutImage{
    
    //创建管理者
    AFHTTPSessionManager *sessionManger = [AFHTTPSessionManager manager];
    
    //设置参数
    
    //发送请求
    
    AcountModel *acount = [AcountModel acountModelFromSandbox];
    
    NSDictionary *parameters = @{
                                 @"access_token":acount.access_token,
                                 @"status":self.inputTextView.text
                                 };
    
    NSString *stringURL = @"https://api.weibo.com/2/statuses/update.json";
    
    [sessionManger POST:stringURL parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"发送成功");
        
        //1.发送界面收回
        //1.1先收回键盘
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        //2.显示发送成功界面
        [SVProgressHUD setStatus:@"发送成功"];
        
        //3.
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@－－发送失败",error);
        [SVProgressHUD setStatus:@"发送失败"];
    }];
    
}



-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    self.photoSelectViewController = segue.destinationViewController;
    
}


#pragma mark - UITextViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    [window endEditing:YES];
    
}



@end
